package br.com.view;

import br.com.dao.ConectaBanco;
import br.com.dao.ModeloTabela;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;

/**
 *
 * @author Cícero
 */
public class Frm_funcao extends javax.swing.JFrame {

    ConectaBanco conexao = new ConectaBanco();    
    
    /**
     * Creates new form Fram
     */
    public Frm_funcao() {
        initComponents();
        conexao.conexao();
         geraTabela("select * from cadastrofuncao order by id_funcao");
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("bancosysepi?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
        cadastrofuncaoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Cadastrofuncao c");
        cadastrofuncaoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : cadastrofuncaoQuery.getResultList();
        cadastrofuncaoQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Cadastrofuncao c");
        cadastrofuncaoList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : cadastrofuncaoQuery1.getResultList();
        jLabel1 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        lblDescricao = new javax.swing.JLabel();
        lblRisco = new javax.swing.JLabel();
        textCodigo = new javax.swing.JTextField();
        textDescricao = new javax.swing.JTextField();
        btnSalvar = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableFuncao = new javax.swing.JTable();
        btnNovo = new javax.swing.JButton();
        lblNome = new javax.swing.JLabel();
        textNome = new javax.swing.JTextField();
        boxRisco = new javax.swing.JComboBox();
        btnPrimeiro = new javax.swing.JButton();
        btnAnterior = new javax.swing.JButton();
        btnProximo = new javax.swing.JButton();
        btnUltimo = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de função");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 22)); // NOI18N
        jLabel1.setText("Cadastro de Função");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 10, -1, -1));

        lblCodigo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblCodigo.setText("Código:");
        lblCodigo.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentRemoved(java.awt.event.ContainerEvent evt) {
                lblCodigoComponentRemoved(evt);
            }
        });
        getContentPane().add(lblCodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, 78, -1));

        lblDescricao.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblDescricao.setText("Descrição:");
        getContentPane().add(lblDescricao, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 130, 78, -1));

        lblRisco.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblRisco.setText("Risco:");
        getContentPane().add(lblRisco, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 160, 78, -1));

        textCodigo.setEnabled(false);
        textCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textCodigoActionPerformed(evt);
            }
        });
        getContentPane().add(textCodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 70, 52, -1));

        textDescricao.setEnabled(false);
        getContentPane().add(textDescricao, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 130, 304, -1));

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (29).png"))); // NOI18N
        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        getContentPane().add(btnSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 460, -1, -1));

        btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (7).png"))); // NOI18N
        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        getContentPane().add(btnAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 460, -1, -1));

        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (3).png"))); // NOI18N
        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });
        getContentPane().add(btnExcluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 460, -1, -1));

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (4).png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 460, -1, -1));

        tableFuncao.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jScrollPane1.setViewportView(tableFuncao);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 190, 500, 203));

        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon(42).png"))); // NOI18N
        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        getContentPane().add(btnNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 460, -1, -1));

        lblNome.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblNome.setText("Nome:");
        getContentPane().add(lblNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, -1, -1));

        textNome.setEnabled(false);
        getContentPane().add(textNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 100, 260, -1));

        boxRisco.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "BAIXO", "MÉDIO", "ALTO" }));
        boxRisco.setEnabled(false);
        getContentPane().add(boxRisco, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 160, 150, -1));

        btnPrimeiro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (43).png"))); // NOI18N
        btnPrimeiro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrimeiroActionPerformed(evt);
            }
        });
        getContentPane().add(btnPrimeiro, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 430, -1, -1));

        btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (2).png"))); // NOI18N
        btnAnterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnteriorActionPerformed(evt);
            }
        });
        getContentPane().add(btnAnterior, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 430, -1, -1));

        btnProximo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (24).png"))); // NOI18N
        btnProximo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProximoActionPerformed(evt);
            }
        });
        getContentPane().add(btnProximo, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 430, -1, -1));

        btnUltimo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (16).png"))); // NOI18N
        btnUltimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUltimoActionPerformed(evt);
            }
        });
        getContentPane().add(btnUltimo, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 430, -1, -1));

        jSeparator1.setForeground(new java.awt.Color(0, 102, 102));
        getContentPane().add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 410, 520, -1));

        jSeparator2.setForeground(new java.awt.Color(0, 102, 102));
        getContentPane().add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 44, 520, -1));

        setSize(new java.awt.Dimension(555, 548));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void lblCodigoComponentRemoved(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_lblCodigoComponentRemoved
        // TODO add your handling code here:
    }//GEN-LAST:event_lblCodigoComponentRemoved

    private void textCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textCodigoActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        conexao.conexao();
        String sqlInserir = ("INSERT INTO cadastrofuncao (nome_funcao, descricao_funcao, nivel_risco) values (?,?,?)");
        try {
            PreparedStatement pst = conexao.con.prepareStatement(sqlInserir);
            pst.setString(1, textNome.getText());
            pst.setString(2, textDescricao.getText());
            pst.setString(3, boxRisco.getSelectedItem().toString());
            pst.execute();
            pst.close();
            JOptionPane.showMessageDialog(null, "Salvo com sucesso!");
            geraTabela("select * from cadastrofuncao order by id_funcao");
            conexao.desconecta();
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "Erro ao Inserir" + erro);
            conexao.desconecta();
        }
        //conexao.desconecta();
        Cancelar();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        Novo();
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        Cancelar();
        conexao.desconecta();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        conexao.conexao();
        String sqlExcluir = (" delete from cadastrofuncao where id_funcao ='" + this.textCodigo.getText() + "'");
        try {
            conexao.executaSQL(sqlExcluir);
            //conexao.pst.close();
            JOptionPane.showMessageDialog(null, "Excluido com Sucesso!");
            geraTabela("select * from cadastrofuncao order by id_funcao");
            conexao.desconecta();
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "Erro ao excluir!" + erro);
            conexao.desconecta();
        }
        //conexao.desconecta();
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        conexao.conexao();
        String sqlAlterar = (" update setor set nome_funcao = ?,descricao_funcao = ?,nivel_risco = ? where id_funcao=? ");
        try {
            PreparedStatement pst = conexao.con.prepareStatement(sqlAlterar);
            pst.setString(1, textNome.getText());
            pst.setString(2, textDescricao.getText());
            pst.setString(3, boxRisco.getSelectedItem().toString());
            pst.setInt(4, Integer.parseInt(textCodigo.getText()));
            pst.executeUpdate();
            pst.close();
            JOptionPane.showMessageDialog(null, "Alterado com Sucesso!");
            geraTabela("select * from cadastrofuncao order by id_funcao");
            conexao.desconecta();
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "Erro ao Alterar" + erro);
            conexao.desconecta();
        }
        //conexao.desconecta();
        Cancelar();
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnPrimeiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrimeiroActionPerformed
        Novo();
        conexao.conexao();
        try {
            conexao.executaSQL("select * from cadastrofuncao");
            conexao.rs.first();
            textCodigo.setText(String.valueOf(conexao.rs.getInt("id_funcao")));
            textNome.setText(conexao.rs.getString("nome_funcao"));
            textDescricao.setText(conexao.rs.getString("descricao_funcao"));
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"erro botao first" +ex);
            conexao.desconecta();
        }
        conexao.desconecta();
    }//GEN-LAST:event_btnPrimeiroActionPerformed

    private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnteriorActionPerformed
        //conexao.conexao();
        try {
            conexao.rs.previous();
            textCodigo.setText(String.valueOf(conexao.rs.getInt("id_funcao")));
            textNome.setText(conexao.rs.getString("nome_funcao"));
            textDescricao.setText(conexao.rs.getString("descricao_funcao"));            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"erro botao previous" +ex);
            conexao.desconecta();
        }
        //conexao.desconecta();
    }//GEN-LAST:event_btnAnteriorActionPerformed

    private void btnProximoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProximoActionPerformed
        //conexao.conexao();
        try {
            conexao.rs.next();
            textCodigo.setText(String.valueOf(conexao.rs.getInt("id_funcao")));
            textNome.setText(conexao.rs.getString("nome_funcao"));
            textDescricao.setText(conexao.rs.getString("descricao_funcao"));
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"erro botao next"+ ex);
            conexao.desconecta();
        }
        //conexao.desconecta();
    }//GEN-LAST:event_btnProximoActionPerformed

    private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUltimoActionPerformed
        Novo();
        conexao.conexao();
        try {
            conexao.executaSQL("select * from cadastrofuncao");
            conexao.rs.last();
            textCodigo.setText(String.valueOf(conexao.rs.getInt("id_funcao")));
            textNome.setText(conexao.rs.getString("nome_funcao"));
            textDescricao.setText(conexao.rs.getString("descricao_funcao"));
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"erro botao last" +ex);
            //conexao.desconecta();
        }
        conexao.desconecta();
    }//GEN-LAST:event_btnUltimoActionPerformed

    public void Novo() {
        textNome.setEnabled(true);
        textDescricao.setEnabled(true);
        boxRisco.setEnabled(true);
        textNome.requestFocus();
    }

    public void Cancelar() {
        textNome.setText("");
        textDescricao.setText("");
        boxRisco.setSelectedIndex(0);
        btnNovo.requestFocus();
        textNome.setEnabled(false);
        textDescricao.setEnabled(false);
        boxRisco.setEnabled(false);
    }

    @SuppressWarnings("empty-statement")

    public void geraTabela(String SQL) {
        ArrayList dados = new ArrayList();
        String[] Colunas = new String[]{"Codigo", "Nome", "Função", "Risco"};
        conexao.executaSQL(SQL);
        try {
            conexao.rs.first();
            do {
                dados.add((new Object[]{conexao.rs.getInt("id_funcao"), conexao.rs.getString("nome_funcao"), conexao.rs.getString("descricao_funcao"), conexao.rs.getString("nivel_risco")}));
            } while (conexao.rs.next());
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao preencher o arrayList" + ex);
        }
        ModeloTabela modeloTabela = new ModeloTabela(dados, Colunas);
        tableFuncao.setModel(modeloTabela);
        tableFuncao.getColumnModel().getColumn(0).setPreferredWidth(180);
        tableFuncao.getColumnModel().getColumn(0).setResizable(false);
        tableFuncao.getColumnModel().getColumn(1).setPreferredWidth(280);
        tableFuncao.getColumnModel().getColumn(1).setResizable(false);
        tableFuncao.getColumnModel().getColumn(2).setPreferredWidth(180);
        tableFuncao.getColumnModel().getColumn(2).setResizable(false);
        tableFuncao.getColumnModel().getColumn(3).setPreferredWidth(180);
        tableFuncao.getColumnModel().getColumn(3).setResizable(false);

        tableFuncao.getTableHeader().setReorderingAllowed(false);
        tableFuncao.setAutoResizeMode(tableFuncao.AUTO_RESIZE_OFF);
        tableFuncao.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    }
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Frm_funcao().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boxRisco;
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnAnterior;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnPrimeiro;
    private javax.swing.JButton btnProximo;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JButton btnUltimo;
    private java.util.List<br.com.model.Cadastrofuncao> cadastrofuncaoList;
    private java.util.List<br.com.model.Cadastrofuncao> cadastrofuncaoList1;
    private javax.persistence.Query cadastrofuncaoQuery;
    private javax.persistence.Query cadastrofuncaoQuery1;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblDescricao;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblRisco;
    private javax.swing.JTable tableFuncao;
    private javax.swing.JTextField textCodigo;
    private javax.swing.JTextField textDescricao;
    private javax.swing.JTextField textNome;
    // End of variables declaration//GEN-END:variables
}
